//
//  SearchShopListController.m
//  takeout
//
//  Created by Mac on 12-5-15.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SearchShopListController.h"
#import "CustomCell.h"
#import "DetailShopViewController.h"
#import "SectionHeaderController.h"
#import "Supplier.h"
#import "SupplierCategory.h"
#import "PublicFunction.h"
#import "UICustomImageView.h"
#import "Constants.h"
@interface SearchShopListController (private)
- (void)refresh;
- (void)stopLoading;
- (void)startLoading;
@end
@implementation SearchShopListController
@synthesize conditions;
@synthesize searchType;
@synthesize supplierCategoryTag;
@synthesize address;
@synthesize isSelling;

- (void) initMembers{
    currentPage = 1;
    suppliers = [recieveDictionary objectForKey:@"Suppliers"];
    fmdbSupplierManager=[[FMDBSupplierManager alloc]init];
    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;	
    if([appDelegate status])
    {
//        //联网，添加到本地
//        NSString *supplierCategoryTagString=[NSString stringWithFormat: @"%d", supplierCategoryTag]; 
//        [fmdbSupplierManager insertSupplierByCategoryId:suppliers supplierCategoryId:supplierCategoryTagString sPage:@"1"];
    }
    
}



//初始化导航栏
-(void)initNav{
    //修改导航栏背景
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"001s.png"] forBarMetrics: UIBarMetricsDefault];
    //定义导航栏左侧按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 54, 27)];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"navBtn.png"] forState:UIControlStateNormal];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"navBtn.png"] forState:UIControlStateHighlighted];
    [leftButton setTitle:@"首 页" forState:UIControlStateNormal]; 
    leftButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14]; 
    
    [leftButton addTarget:self action:@selector(backButtonPressd:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [leftButton release];
    self.navigationItem.leftBarButtonItem = leftItem;
    [leftItem release];
}







- (void)viewDidLoad {   
    
    UIView *tbView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320,540)];  
    //自定识别头及高度  
    tbView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight;  
    tbView.backgroundColor = [UIColor whiteColor];  
    //将view添加到主窗体  
    [self.view addSubview:tbView]; 
    
    tableViews=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 540)];  
    tableViews.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight;  
    tableViews.backgroundColor=[UIColor whiteColor];  
    //添加到view窗体上  
    [tbView addSubview:tableViews];  
    [tbView release];
    tableViews.delegate=self;  
    tableViews.dataSource=self; 
    //初始化导航栏
    [self initNav];
    //设置视图title
    self.title=@"商家列表";
    [super viewDidLoad];
}

- (void)backButtonPressd:(id)sender{
    //将当前视图推出栈，程序将进入上一视图
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    //设置显示导航栏
    self.navigationController.navigationBarHidden = NO; 
    
    
    
}

/*************************/ 
/*       商家列表视图       */
/**************************/

//返回表试图分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [suppliers count];
}




//设置表试图每行显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger index=indexPath.row;
    Supplier *supplier=[suppliers objectAtIndex:index];
    static NSString *CellIdentifier = @"CustomCell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    
	if(cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        //设置单元格背景图片
        UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"011s.png"]];
        cell.backgroundView = bgImageView;    
        [bgImageView release];
    }    
    
    
    UICustomImageView *imageView = (UICustomImageView *)[cell.contentView viewWithTag:100];
    if (imageView == nil) {
        UIImageView* imgBg=[[UIImageView alloc] initWithFrame:CGRectMake(5,5,85,85)];
        [imgBg setImage:[UIImage imageNamed:@"ImgBg.png"]];  
        [imgBg setUserInteractionEnabled:YES];  
        [cell.contentView addSubview:imgBg];
        [imgBg release];
        
        imageView = [[UICustomImageView alloc] initWithFrame:CGRectMake(9, 8, 77, 77)];
        [imageView setContentMode:UIViewContentModeScaleAspectFit];
        [imageView setUserInteractionEnabled:NO];
        [imageView setTag:100];
        [cell.contentView addSubview:imageView];
        [imageView release];
    }
    [imageView setImage:nil];
    [imageView setImageURL:supplier.imgUrl];
    imageView.image = [PublicFunction resizeImage:imageView.image newSize:CGSizeMake(60,60)];
    
    
    UILabel *shopNameLabel = (UILabel *)[cell.contentView viewWithTag:200];
    if (shopNameLabel == nil) {
        shopNameLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];
        shopNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(95, 7, 200, 16)];
        [shopNameLabel setText:supplier.supplierName];
        [shopNameLabel setFont:[UIFont boldSystemFontOfSize:16]];
        [shopNameLabel setBackgroundColor:[UIColor clearColor]];
        shopNameLabel.tag = 200;
        [cell.contentView addSubview:shopNameLabel];
        [shopNameLabel release];
    }
    //设置商铺名长度
    if(supplier.supplierName.length>7){
        NSString *supplierNameShort = [supplier.supplierName substringToIndex:7];
        [supplier setSupplierName:supplierNameShort];
    }
    [shopNameLabel setText:supplier.supplierName];
    
    UILabel *shopDescLabel = (UILabel *)[cell.contentView viewWithTag:204];
    if (shopDescLabel == nil) {
        shopDescLabel = [[UILabel alloc] initWithFrame:CGRectMake(95, 33, 120, 14)];
        shopDescLabel.font=[UIFont fontWithName:@"Helvetica" size:14];
        [shopDescLabel setBackgroundColor:[UIColor clearColor]];
        shopDescLabel.tag = 204;
        [cell.contentView addSubview:shopDescLabel];
        [shopDescLabel release];
    }
    [shopDescLabel setText:supplier.desc];
    
    UILabel *shopTypeLable=(UILabel *)[cell.contentView viewWithTag:202];
    if (shopTypeLable == nil) {
        shopTypeLable = [[UILabel alloc] initWithFrame:CGRectMake(95, 51, 200, 14)];
        shopTypeLable.font=[UIFont fontWithName:@"Helvetica" size:14];
        [shopTypeLable setBackgroundColor:[UIColor clearColor]];
        shopTypeLable.tag = 202;
        [cell.contentView addSubview:shopTypeLable];
        [shopTypeLable release];
    }
    NSString *supCateIdToString = [NSString stringWithFormat:@"%d         人均:",supplier.supCateId];
    [shopTypeLable setText:supCateIdToString];
    
    UILabel *shopAvgPriceLable=(UILabel *)[cell.contentView viewWithTag:203];
    if (shopAvgPriceLable == nil) {
        shopAvgPriceLable = [[UILabel alloc] initWithFrame:CGRectMake(180, 51, 100, 14)];
        shopAvgPriceLable.font=[UIFont fontWithName:@"Helvetica" size:14];
        //自定义颜色
        [shopAvgPriceLable setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
        
        [shopAvgPriceLable setBackgroundColor:[UIColor clearColor]];
        shopAvgPriceLable.tag = 203;
        [cell.contentView addSubview:shopAvgPriceLable];
        [shopAvgPriceLable release];
    }
    NSString *avgPrice=[NSString stringWithFormat:@"%.2f",supplier.avgPrice];
    [shopAvgPriceLable setText:avgPrice];
    
    UILabel *shopAddressLabel = (UILabel *)[cell.contentView viewWithTag:201];
    if (shopAddressLabel == nil) {
        shopAddressLabel = [[UILabel alloc] initWithFrame:CGRectMake(95, 69, 200, 14)];
        shopAddressLabel.font=[UIFont fontWithName:@"Helvetica" size:14];
        [shopAddressLabel setBackgroundColor:[UIColor clearColor]];
        shopAddressLabel.tag = 201;
        [cell.contentView addSubview:shopAddressLabel];
        [shopAddressLabel release];
    }
    
    [shopAddressLabel setText:supplier.address];
    
    UIButton *phoneButton = (UIButton *)[cell.contentView viewWithTag:300];
    if (phoneButton == nil) {
        phoneButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
        [phoneButton setFrame:CGRectMake(240, 7, 50, 55)];
        UIImage *image = [UIImage imageNamed:@"phoneImg.png"]; 
        [phoneButton setBackgroundImage:image forState:UIControlStateNormal]; 
        phoneButton.tag = 300;
        [phoneButton addTarget:self action:@selector(callAction:event:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:phoneButton];
        //点击拨号按钮直接拨号
    }
    
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    cell.tag = supplier.supplierId;
    
    return cell;
    
}

//定义点击拨号按钮时的操作 
- (void)callAction:(id)sender event:(id)event{ 
    NSSet *touches = [event allTouches]; 
    UITouch *touch = [touches anyObject]; 
    CGPoint currentTouchPosition = [touch locationInView:tableViews]; 
    NSIndexPath *indexPath = [tableViews indexPathForRowAtPoint: currentTouchPosition]; 
    if (indexPath == nil) { 
        return; 
    } 
    NSUInteger  row = [indexPath row]; 
    Supplier *rowData = [suppliers objectAtIndex:row]; 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拨打电话" message:@"请选择要拨打的号码" delegate:self cancelButtonTitle:@"取  消" otherButtonTitles:nil];
    if(rowData.phone.length != 0){
        [alert addButtonWithTitle:rowData.phone];
    }
    if(rowData.phone2.length != 0){
        [alert addButtonWithTitle:rowData.phone2];
    }
    if(rowData.telephone.length != 0){
        [alert addButtonWithTitle:rowData.telephone];
    }
    if(rowData.telephone2.length != 0){
        [alert addButtonWithTitle:rowData.telephone2];
    } 
    alert.tag = 1;
	[alert show];
	[alert release];
    
}

//根据被点击按钮的索引处理点击事件  
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {  
    //tag为1时为点击拨号按钮时弹出的对话框
    if(alertView.tag == 1){
        NSString *number = [alertView buttonTitleAtIndex:buttonIndex];
        //phoneNumber为号码字符串 
        NSString *phoneNumber = [NSString stringWithFormat:@"tel://%@",number]; 
        //拨号 
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]]; 
    }
}



//选中Cell响应事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//选中后的反显颜色即刻消失
    
    CustomCell *cell = (CustomCell *)[tableView cellForRowAtIndexPath:indexPath];
    NSString *supplierId = [NSString stringWithFormat:@"%d",cell.tag];
    manager = [[SupplierManager alloc] init];
    Supplier *supplierDetail;
    if([appDelegate status]){
        //联网
        supplierDetail = [manager getSupplierDetailById:supplierId];
    }
    else{
        //离线
        supplierDetail=[fmdbSupplierManager getSupplierDetailByIdFromLoc:supplierId];
    }
    
    if (supplierDetail == nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"没有该商家的详细信息" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        return;
    }
    
    //创建新的试图并将试图推入栈中
    DetailShopViewController *detailShopViewController = [[DetailShopViewController alloc]initWithNibName:@"DetailShopViewController" bundle:nil];
    UINavigationController  *theNavController = [[UINavigationController alloc]
                                                 initWithRootViewController:detailShopViewController];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :2];
    [dictionary setObject:supplierId forKey:@"supId"];
    [dictionary setObject:supplierDetail forKey:@"Supplier"];
    
    [detailShopViewController setRecieveDictionary:dictionary];
    
    [detailShopViewController release];
    theNavController.navigationBar.tintColor = [UIColor blackColor];
    [self.navigationController pushViewController: detailShopViewController animated:YES];
    [theNavController release];
    
    
    
}



//设置表试图行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath   
{
    return 95;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 80;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    NSArray *nils = [[NSBundle mainBundle]loadNibNamed:@"RefreshView" owner:self options:nil];
    refreshView = [nils objectAtIndex:0];
    [refreshView setupWithOwner:tableView delegate:self];
    refreshView.isPullUp = YES;
    refreshView.hidden = YES;
    return refreshView;
}

/************************/ 
/*     索搜类型选取器      */
/************************/




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {

}

- (void)dealloc {
    [tableViews release];
    if (manager!=nil) {
        [manager release];
    }
    [suppliers release];
    [refreshView release];
    //    [super dealloc];
}

// 停止，可以触发自己定义的停止方法
- (void)stopLoading {
    [tableViews reloadData];
    [refreshView stopLoading];
}
// 开始，可以触发自己定义的开始方法
- (void)startLoading {
    refreshView.hidden = NO;
    [refreshView startLoading];
    // 模拟3秒后停止
    
    if (!isEnd) {
        currentPage++;
        if (manager == nil) {
            manager = [[SupplierManager alloc] init];
        }
        NSArray *newSuppliers=nil;
        NSString *currentPageString=[NSString stringWithFormat: @"%d", currentPage];
        NSString *supplierCategoryTagString=[NSString stringWithFormat: @"%d", supplierCategoryTag];
        
        NSLog(@"搜索类型%@",searchType);
        NSLog(@"条件%@",conditions);
        
        //直接搜索
        if(searchType==@"0"){
            if([appDelegate status]){
                //联网状态
//              newSuppliers=nil;
                //离线
                newSuppliers=[fmdbSupplierManager getSuppliersByNameOrDishAndPage:conditions sPage:currentPageString];
            }
            else{
                //离线
                newSuppliers=[fmdbSupplierManager getSuppliersByNameOrDishAndPage:conditions sPage:currentPageString];

            }
        }
        //详细搜索
        if(searchType==@"1"){
            if([appDelegate status]){
                //联网
                newSuppliers = [manager getSupplier:[NSString stringWithFormat:@"%d",supplierCategoryTag] pageIndex:currentPage road:address isSelling:isSelling];
                //添加到本地
                [fmdbSupplierManager insertSupplierByCategoryId:suppliers supplierCategoryId:supplierCategoryTagString sPage:currentPageString];
            }
            else{
                //离线
                newSuppliers=[fmdbSupplierManager getSuppliersByNameOrDishAndPage:conditions sPage:currentPageString];
            }

        }
        
        if (newSuppliers != nil) {
            suppliers = [[suppliers arrayByAddingObjectsFromArray:newSuppliers] retain];
        }else{
            isEnd = YES;
        }
    }
    
    [self performSelector:@selector(stopLoading) withObject:nil afterDelay:3];
}
// 刷新
- (void)refresh {
    [self startLoading];
}
#pragma mark - RefreshViewDelegate
- (void)refreshViewDidCallBack {
    [self refresh];
}
#pragma mark - UIScrollView 
// 刚拖动的时候
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [refreshView scrollViewWillBeginDragging:scrollView];
}
// 拖动过程中
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [refreshView scrollViewDidScroll:scrollView];
}
// 拖动结束后
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [refreshView scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
}


@end
